﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

using System.Drawing;
using System.Globalization;
using System.Collections.Generic;
using MapCenterSystem.DataInfo;
using MapCenterSystem.DefineType;
using MapCenterSytem.Process;
using MapCenterSystem.Utility;

using System.Threading;
using System.Resources;

namespace MobiMap.Guest
{
    public partial class ResultStartPoint : System.Web.UI.Page
    {
        private string strStartPoint = string.Empty;
        private string strEndPoint = string.Empty;

        ResourceManager rm;
        CultureInfo ci;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                HtmlControl divToolbarWrapper = (HtmlControl)Master.FindControl("divToolbarWrapper");
                divToolbarWrapper.Style["top"] = "6px";

                HtmlControl divToolbar = (HtmlControl)Master.FindControl("divToolbar");
                divToolbar.Style["display"] = "none";

                //Panel divEdge = (Panel)Master.FindControl("divEdge");
                //LiteralControl imgEdge = (LiteralControl)divEdge.Controls[0];
                //imgEdge.Text = "<div><img id=\"idEdge\" src=\"../Image/Expand.png\"  alt=\"edge\"/></div>";

                int pageSize = 5;
                if (Request.Cookies["mobimap_scrHeight"] != null)
                {
                    int scrHeight = int.Parse(Request.Cookies["mobimap_scrHeight"].Value);
                    if (scrHeight > 512)
                        scrHeight = 512;

                    pageSize = (scrHeight - 150) / 34;
                }

                gvAddress.PageSize = pageSize;
                gvService.PageSize = pageSize;

                if (Session["mobimap_direction"] != null)
                {
                    string[] arr = (string[])Session["mobimap_direction"];
                    strStartPoint = arr[0];
                    strEndPoint = arr[1];

                    lbKeyWord.Text = strStartPoint;
                }
                else
                {
                    Response.Redirect("Home.aspx");
                    return;
                }

                Cache.Remove("mobimap_listAddress");
                Cache.Remove("mobimap_listService");
                BindListAddress(strStartPoint);
                BindListService(strStartPoint);

                Session.Remove("mobimap_CurrentList");
            }
            else
            {
                FillKeyword();

                if (Session["mobimap_CurrentList"] != null)
                {
                    if ((string)Session["mobimap_CurrentList"] == "address")
                    {
                        SetAddressTab();
                    }
                    else if ((string)Session["mobimap_CurrentList"] == "service")
                    {
                        SetServiceTab();
                    }
                }
            }

            //Language
            SetLanguage();
        }

        public void SetAddressTab()
        {
            gvAddressContainer.Style["display"] = "block";
            gvServiceContainer.Style["display"] = "none";

            tabAddress.Attributes.Add("class", "tab_active");
            tabService.Attributes.Add("class", "tab_normal");
        }

        public void SetServiceTab()
        {
            gvAddressContainer.Style["display"] = "none";
            gvServiceContainer.Style["display"] = "block";

            tabService.Attributes.Add("class", "tab_active");
            tabAddress.Attributes.Add("class", "tab_normal");
        }

        public void SetLanguage()
        {
            rm = new ResourceManager("Resources.SiteMap", System.Reflection.Assembly.Load("App_GlobalResources"));
            HtmlImage imgLanguage = (HtmlImage)Master.FindControl("idLanguage");
            if (Request.Cookies["language"] != null)
            {
                string language = Request.Cookies["language"].Value;
                Thread.CurrentThread.CurrentCulture = new CultureInfo(language);
                LoadString(Thread.CurrentThread.CurrentCulture);

                imgLanguage.Src = "../Image/" + language + ".png";
                return;
            }

            //Defaut language is Vietnamese
            Thread.CurrentThread.CurrentCulture = new CultureInfo("vi-VN");
            ci = Thread.CurrentThread.CurrentCulture;
            LoadString(ci);
            imgLanguage.Src = "../Image/" + "vi-VN" + ".png";
        }

        public void LoadString(CultureInfo ci)
        {
            tabAddress.InnerHtml = rm.GetString("TabResult_Address", ci);
            tabService.InnerHtml = rm.GetString("TabResult_Service", ci);
        }

        private bool existAddress = false;
        public void BindListAddress(String keyword)
        {
            IList<HomeInfoEx> lstHomeInfo = new List<HomeInfoEx>();
            if (Cache["mobimap_listAddress"] == null)
            {
                List<string> lst = StringHelper.GetNumberAndStreet(keyword);
                string area = StringHelper.GetSearchString(lst[1], AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["abbr_file"]);
                lstHomeInfo = HomeBUS.FindExactAddress(lst[0], area);
                if (lstHomeInfo.Count == 0)
                {
                    lstHomeInfo = HomeBUS.FindNearAddress(StringHelper.GetExactNumber(lst[0]), area);
                }
                Cache["mobimap_listAddress"] = lstHomeInfo;
            }
            else
            {
                lstHomeInfo = (IList<HomeInfoEx>)Cache["mobimap_listAddress"];
            }

            if (lstHomeInfo.Count > 0)
            {
                gvAddress.DataSource = lstHomeInfo;
                gvAddress.DataBind();
                existAddress = true;
                SetAddressTab();
            }
            else
            {
                SetServiceTab();
            }
        }

        public void BindListService(String keyword)
        {
            keyword = StringHelper.GetSearchString(keyword, AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["abbr_file"]);
            IList<PlaceInfo> lstPlaceInfo = new List<PlaceInfo>();
            if (Cache["mobimap_listService"] == null)
            {
                lstPlaceInfo = PlaceEx.GetPlaceByKeyword(keyword);
                Cache["mobimap_listService"] = lstPlaceInfo;
            }
            else
            {
                lstPlaceInfo = (IList<PlaceInfo>)Cache["mobimap_listService"];
            }

            if (lstPlaceInfo.Count > 0)
            {
                gvService.DataSource = lstPlaceInfo;
                gvService.DataBind();
                if(!existAddress)
                    SetServiceTab();
            }
            else
            {
                SetAddressTab();
            }
        }



        private int _iRow = 0;
        protected void gvAddress_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {                
                _iRow++;

            }

        }

        public void FillKeyword()
        {
            if (Session["mobimap_direction"] != null)
            {
                string[] arr = (string[])Session["mobimap_direction"];
                strStartPoint = arr[0];
                strEndPoint = arr[1];
            }
            lbKeyWord.Text = strStartPoint;
        }

        public string GetRows()
        {
            return this._iRow.ToString();
        }

        public void lbtAddress_Click(Object sender, EventArgs e)
        {
            LinkButton link = (LinkButton)sender;
            Control selectedRow = (Control)link.Parent;

            Label lbNumber = (Label)selectedRow.FindControl("lbNumber");
            Label lbArea = (Label)selectedRow.FindControl("lbArea");
            Label lbLong = (Label)selectedRow.FindControl("lbLongitude");
            Label lbLat = (Label)selectedRow.FindControl("lbLatitude");

            string number = lbNumber.Text;
            string street = "";
            string area = lbArea.Text;
            string longitude = lbLong.Text;
            string latitude = lbLat.Text;

            string[] homeInfo = { number + " " + street + " " + area, "", longitude, latitude };
            Session["mobimap_startinfo"] = homeInfo;
            string url = "ResultEndPoint.aspx";
            if (Session["mobimap_endinfo"] != null)
            {
                string[] endInfo = (string[])Session["mobimap_endinfo"];
                Coordinate endPoint = new Coordinate(double.Parse(endInfo[3], CultureInfo.InvariantCulture),
                                                       double.Parse(endInfo[2], CultureInfo.InvariantCulture));
                Coordinate startPoint = new Coordinate(double.Parse(latitude, CultureInfo.InvariantCulture),
                                                     double.Parse(longitude, CultureInfo.InvariantCulture));

                List<GraphNodeInfoEx> lstNode = GraphNode.ShortestPath(startPoint, endPoint);
                Session["mobimap_lstGraphNode"] = lstNode;

                url = "Home.aspx";
            }
            Response.Redirect(url);
        }

        public void lbtService_Click(Object sender, EventArgs e)
        {
            LinkButton link = (LinkButton)sender;
            Control selectedRow = (Control)link.Parent;

            Label lbFullName = (Label)selectedRow.FindControl("lbFullName");
            Label lbAddress = (Label)selectedRow.FindControl("lbAddress");
            Label lbLong = (Label)selectedRow.FindControl("lbLongitude");
            Label lbLat = (Label)selectedRow.FindControl("lbLatitude");
            Label lbID = (Label)selectedRow.FindControl("serID");

            string[] serviceInfo = { lbFullName.Text, lbAddress.Text, lbLong.Text, lbLat.Text, lbID.Text };
            Session["mobimap_startinfo"] = serviceInfo;

            string url = "ResultEndPoint.aspx";
            if (Session["mobimap_endinfo"] != null)
            {
                string[] endInfo = (string[])Session["mobimap_endinfo"];
                Coordinate endPoint = new Coordinate(double.Parse(endInfo[3], CultureInfo.InvariantCulture),
                                                       double.Parse(endInfo[2], CultureInfo.InvariantCulture));
                Coordinate startPoint = new Coordinate(double.Parse(lbLat.Text, CultureInfo.InvariantCulture),
                                                     double.Parse(lbLong.Text, CultureInfo.InvariantCulture));

                List<GraphNodeInfoEx> lstNode = GraphNode.ShortestPath(startPoint, endPoint);
                Session["mobimap_lstGraphNode"] = lstNode;

                url = "Home.aspx";
            }
            Response.Redirect(url);
        }

        protected void gvAddress_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvAddress.PageIndex = e.NewPageIndex;
            BindListAddress(strStartPoint);
            FillKeyword();

            Session["mobimap_CurrentList"] = "address";
        }

        protected void gvService_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvService.PageIndex = e.NewPageIndex;
            BindListService(strStartPoint);
            FillKeyword();

            Session["mobimap_CurrentList"] = "address";
        }

        
    }
}
